import React, {useState, forwardRef, useImperativeHandle, useRef, useEffect} from 'react';
import {Button, Divider, message, Modal, Spin} from "antd";
import VoiceMessage from './VoiceMessage/VoiceMessage'
import {getBlogCommentList, addBlogComment} from "./commentsSectionApi"
import ReplyAndPublish from "../../component/ReplyAndPublish/ReplyAndPublish";
import {useLocation} from "react-router-dom";
import {store} from "../../store/store";

// 评论弹窗
const CommentsSection = forwardRef((props, ref) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [messageList, setMessageList] = useState([])
    const [listQuery, setListQuery] = useState({page: 1, limit: 10})
    const [spinState, setSpinState] = useState(false)
    const Location = useLocation()
    const ReplyAndPublishRef = useRef()
    const blogId = Location.search.split("=")[1]
    const [updateStatus, setUpdateStatus] = useState(0)

    //提交或回复评论的api
    const submitMessage = (text) => {
        const commentsData = {
            commentContent: text,
            blogTextId: blogId,
            blogUserId: store.getState().UserRedux.user.id,
            parentId: null
        }

        addBlogComment(commentsData).then(res => {
            if (res.code === '200') {
                message.success('评论成功')
                setUpdateStatus(updateStatus + 1)
            } else {
                message.error('评论失败')
            }
        }).catch(() => {
            message.error('评论失败')
        })
    }

    //打开输入框
    const threadedComment = () => {
        ReplyAndPublishRef.current.showModal()
    }

    //取消自己
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //打开自己
    const showModal = () => {
        getMessageFun()
        setIsModalOpen(true);
    };

    //获取评论
    const getMessageFun = () => {
        setSpinState(true)
        const searchData = {blogTextId: blogId}
        getBlogCommentList({searchData, listQuery}).then(res => {
            if (res.code === '200') {
                if (listQuery.page === 1) {
                    setMessageList(res.data)
                } else {
                    setMessageList([...messageList, ...res.data])
                }
            } else {
                message.error('获取留言失败')
            }
        }).catch(e => {
            message.error('获取留言失败')
        }).finally(() => {
            setSpinState(false)
        })
    }


    //查看更多
    const getMore = () => {
        setListQuery({...listQuery, page: listQuery.page + 1})
    }

    // 页面初始化和获取更多数据
    useEffect(() => {
        getMessageFun()
    }, [listQuery, updateStatus])

    //抛出数据给父组件调用
    useImperativeHandle(ref, () => {
        return {
            showModal
        }
    })
    return (
        <>
            <Modal
                title="评论~~"
                width='1500px'
                open={isModalOpen}
                threadedComment
                onCancel={handleCancel}
                footer={[
                    <Button key="back" onClick={handleCancel}>
                        关闭
                    </Button>,
                    <Button key="submit" type="primary" onClick={threadedComment}>
                        我也来一条~~
                    </Button>
                ]}
            >
                <div style={{padding: '20px', height: '60vh', overflow: 'auto'}}>
                    {messageList.map((i) => {
                        return (
                            <div key={i.id}>
                                <VoiceMessage
                                    blogId={blogId}
                                    item={i}>
                                </VoiceMessage>
                                <Divider/>
                            </div>
                        )
                    })}
                    <div style={{textAlign: "center", fontSize: '0.7rem', color: '#26bbf1', marginTop: '1rem'}}>
                        <span style={{cursor: "pointer"}} onClick={getMore}>
                            {!spinState ? '获取更多' : <Spin/>}
                        </span>
                    </div>
                </div>
            </Modal>
            <ReplyAndPublish submitMessage={submitMessage}
                             title={'评论发表~~'}
                             maxLength={500}
                             ref={ReplyAndPublishRef}>
            </ReplyAndPublish>
        </>
    );
})

export default CommentsSection;
